package com.fenghuajueli.module_user.vip

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ConvertUtils
import com.fenghuajueli.libbasecoreui.constants.AppConfigInfo
import com.fenghuajueli.libbasecoreui.constants.PrivacyConstantsUtils
import com.fenghuajueli.libbasecoreui.data.entity.goods.GoodsEntity
import com.fenghuajueli.libbasecoreui.recycler.setOnFastClickListener
import com.fenghuajueli.libbasecoreui.upload.UploadUtils.payAction
import com.fenghuajueli.libbasecoreui.utils.CustomItemDecoration
import com.fenghuajueli.module_route.UserModuleRoute
import com.fenghuajueli.module_user.R
import com.fenghuajueli.module_user.adapter.VipDescAdapter
import com.fenghuajueli.module_user.adapter.VipPriceAdapter
import com.fenghuajueli.module_user.databinding.ActivityOpenVipBinding
import com.fenghuajueli.module_user.dialog.SubscribeDialog
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * @Author: sz_ijj
 * @Date: 2024-01-10 14:58
 **/
@Route(path = UserModuleRoute.USER_OPEN_VIP_ACTIVITY)
class UiVipActivity : BaseVipActivity() {
    private val binding by lazy { ActivityOpenVipBinding.inflate(layoutInflater) }
    private val vipPriceAdapter by lazy {
        VipPriceAdapter(this, emptyList()).apply {
            setOnItemClick { _, data ->
                viewModel.setCurrentGood(data)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        initView()
        initData()
        initVipDesc()
        initPrivacy()
    }

    //支付成功接入归因
    override fun initUpload() {
        viewModel.currentGood.value?.let {
            payAction(this@UiVipActivity, application, it.goods_price)
        }
    }

    private fun initView() {
        with(binding) {
            btnBack.setOnClickListener { onBackPressed() }
            btnBuyKnow.setOnFastClickListener { toPrivacyWeb() }
            checkView.setOnFastClickListener { viewModel.checkCurrentGoods() }
            btnAliPay.setOnFastClickListener { viewModel.checkPayChannel(AppConfigInfo.PAY_CHANNEL_ZFB) }
            btnWechatPay.setOnFastClickListener { viewModel.checkPayChannel(AppConfigInfo.PAY_CHANNEL_WECHAT) }
            btnPay.setOnFastClickListener { toPay() }
        }
    }

    private fun initData() {
        lifecycleScope.launch {
            launch {
                viewModel.goodsList
                    .flowWithLifecycle(lifecycle, Lifecycle.State.CREATED)
                    .collectLatest {
                        if (it.isNotEmpty())
                            vipPriceAdapter.refreshData(it)
                    }
            }

            launch {
                viewModel.buttonUiState
                    .flowWithLifecycle(lifecycle, Lifecycle.State.CREATED)
                    .collectLatest { uiState ->
                        with(binding) {
                            btnAliPay.isVisible = uiState.aliPay
                            btnWechatPay.isVisible = uiState.wechatPay
                            with(!uiState.subscribe){
                                tvSubscribe.isInvisible = this
                                llCheckView.isInvisible = this
                                btnBuyKnow.isVisible = this
                            }
                            checkView.isSelected = uiState.isCheck

                            if (uiState.payChannel == AppConfigInfo.PAY_CHANNEL_ZFB) {
                                btnAliPay.isChecked = true
                                btnWechatPay.isChecked = false
                            } else {
                                btnAliPay.isChecked = false
                                btnWechatPay.isChecked = true
                            }
                        }
                    }
            }

            launch {
                viewModel.currentGood
                    .flowWithLifecycle(lifecycle, Lifecycle.State.CREATED)
                    .collectLatest {
                        initSubscribeText()
                    }
            }
        }
    }

    @SuppressLint("DiscouragedApi")
    private fun initVipDesc() {
        binding.rclGoods.setLayoutManager(
            LinearLayoutManager(
                this@UiVipActivity,
                LinearLayoutManager.HORIZONTAL,
                false
            )
        )
        val vipItemDecoration = CustomItemDecoration(
            this@UiVipActivity,
            ConvertUtils.dp2px(2f).toFloat(),
            ConvertUtils.dp2px(6f).toFloat()
        )
        binding.rclGoods.addItemDecoration(vipItemDecoration)
        binding.rclGoods.adapter = vipPriceAdapter

        val functionList = ArrayList<Int>()
        val img = getResources().getIdentifier("user_icon_function_01", "mipmap", packageName)
        if (img == 0) {
            binding.rclFunctions.visibility = View.GONE
            binding.ivFunctionsTitle.setVisibility(View.GONE)
        } else {
            binding.rclFunctions.visibility = View.VISIBLE
            binding.ivFunctionsTitle.setVisibility(View.VISIBLE)
        }
        for (i in 0..9) {
            val imgResId = getResources().getIdentifier(
                "user_icon_function_0" + (i + 1), "mipmap",
                packageName
            )
            if (imgResId == 0) {
                continue
            }
            functionList.add(imgResId)
        }
        val linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        binding.rclFunctions.setLayoutManager(linearLayoutManager)
        val customItemDecoration = CustomItemDecoration(
            this,
            ConvertUtils.dp2px(22f).toFloat(),
            ConvertUtils.dp2px(15f).toFloat()
        )
        binding.rclFunctions.addItemDecoration(customItemDecoration)
        val vipDescAdapter = VipDescAdapter(functionList)
        binding.rclFunctions.setAdapter(vipDescAdapter)
    }

    private fun initPrivacy() {
        val first = "同意 "
        val second = "《会员服务协议》"
        val third = "《订阅协议》"
        val spannableString = SpannableString(first + second + "和" + third)
        var clickableSpan: ClickableSpan = object : ClickableSpan() {
            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.setColor(ContextCompat.getColor(this@UiVipActivity, R.color.priviceTextColor))
                //超链接形式的下划线，false 表示不显示下划线，true表示显示下划线,其实默认也是true，如果要下划线的话可以不设置
                ds.isUnderlineText = false
            }

            override fun onClick(widget: View) {
                toPrivacyWeb()
            }
        }
        spannableString.setSpan(
            clickableSpan,
            first.length,
            first.length + second.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        clickableSpan = object : ClickableSpan() {
            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.setColor(ContextCompat.getColor(this@UiVipActivity, R.color.priviceTextColor))
                ds.isUnderlineText = false
            }

            override fun onClick(widget: View) {
                toPrivacyWeb(PrivacyConstantsUtils.ProtocolType.SUBSCRIBE_PROTOCOL)
            }
        }
        spannableString.setSpan(
            clickableSpan,
            first.length + second.length + 1,
            spannableString.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        binding.tvPrivacy.text = spannableString
        binding.tvPrivacy.highlightColor = Color.TRANSPARENT
        binding.tvPrivacy.movementMethod = LinkMovementMethod.getInstance()
    }

    private fun initSubscribeText() {
        checkNotNullCurrentGoods {
            val builder: SpannableStringBuilder = getSubscribeTextBuilder(it)
            binding.tvSubscribe.text = builder
            binding.tvSubscribe.movementMethod = LinkMovementMethod.getInstance()
        }
    }

    private fun getSubscribeTextBuilder(currentGood: GoodsEntity): SpannableStringBuilder {
        val text = when (currentGood.vip_type) {
            105 -> currentGood.goods_desc + " 《订阅须知》"
            1011 -> "7天试用到期自动续费包年会员，可随时取消 《订阅须知》"
            else -> "到期自动续费：¥" + currentGood.renew_price + "  可随时取消 《订阅须知》"
        }

        val builder = SpannableStringBuilder(text)
        val clickableSpan: ClickableSpan = object : ClickableSpan() {
            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.setColor(ContextCompat.getColor(this@UiVipActivity,
                        R.color.vipCenterSubTextColor))
                //超链接形式的下划线，false 表示不显示下划线，true表示显示下划线,其实默认也是true，如果要下划线的话可以不设置
                ds.isUnderlineText = false
            }

            override fun onClick(widget: View) {
                val dialog = SubscribeDialog(this@UiVipActivity)
                dialog.show()
            }
        }
        builder.setSpan(clickableSpan,
            text.length - 6, text.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        return builder
    }
}